package com.ccx.coachsite.bus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.ccx.coachsite.http.BaseResp;
import com.ccx.coachsite.http.HttpRequest;
import com.ccx.coachsite.http.UrlConfig;
import com.ccx.coachsite.util.SharedPreferencesUtil;
import com.ccx.coachsite.util.StringUtil;

public class ExpertProvider {

	public final static int NoClaimed = 532;

	private int errorCode = 200;
	private String lastErrorMessage;
	private int expertTotalPage = -1;
	private static ExpertProvider instance;

	public static ExpertProvider getInstance() {
		if (instance == null)
			instance = new ExpertProvider();
		return instance;
	}

	public int getLastErrorCode() {
		return errorCode;
	}

	public String getLastErrorMessage() {
		return lastErrorMessage;
	}

	public int getExpertTotalPage() {
		return expertTotalPage;
	}

	public ExpertInfo loadMyExpert(Context context) {
		try {
			// Account acount = AccountMgr.readAccountInfo(context);
			String mobile = SharedPreferencesUtil.getValue(context,
					SharedKey.Shared_Mobile_Key, "");
			String url = String.format(
					UrlConfig.getUrlByKey(UrlConfig.GetMyExpertUrlKey), mobile);
			BaseResp br = HttpRequest.DoHttpRequest(url);
			if (br.isSuccess()) {
				JSONObject data = new JSONObject(br.getResponse());
				ExpertInfo expert = new ExpertInfo();
				expert.setId(data.optInt("userId"));
				expert.setIcon(data.optString("icon"));
				expert.setName(data.optString("nickName"));
				expert.setPhone(data.optString("phone"));
				expert.setRole(data.optString("levelName"));
				String qq = data.optString("qq");
				if (!JSONTextUtils.isEmpty(qq))
					expert.setQQ(data.optString("qq"));
				else
					expert.setQQ("未设置");
				return expert;
			} else {
				errorCode = Integer.valueOf(br.getErrorCode());
			}
		} catch (Exception e) {

		}
		return null;
	}

	public List<ExpertInfo> loadExpertList(Context context, int page) {
		try {
			Account account = AccountMgr.readAccountInfo(context);

			List<ExpertInfo> experts = new ArrayList<ExpertInfo>();
			String url = String.format(
					UrlConfig.getUrlByKey(UrlConfig.GetExpertListUrlKey), page,
					account.getMobile());
			BaseResp br = HttpRequest.DoHttpRequest(url);
			if (br.isSuccess()) {
				JSONObject data = new JSONObject(br.getResponse());
				expertTotalPage = data.optInt("totalPages");
				JSONArray array = data.optJSONArray("list");
				for (int i = 0; i < array.length(); i++) {
					JSONObject expertData = array.getJSONObject(i);
					ExpertInfo expert = new ExpertInfo();
					expert.setId(expertData.optInt("id"));
					expert.setIcon(expertData.optString("icon"));
					expert.setName(expertData.optString("nickName"));
					expert.setPhone(expertData.optString("phone"));
					if (expert.getId() == account.getUserId())
						continue;
					experts.add(expert);
				}
			}
			return experts;
		} catch (Exception e) {

		}
		return null;
	}

	public List<ExpertMessage> loadExpertMessages(Context context,
			ExpertInfo expert) {
		try {
			Account account = AccountMgr.readAccountInfo(context);
			List<ExpertMessage> messages = new ArrayList<ExpertMessage>();
			String url = String.format(
					UrlConfig.getUrlByKey(UrlConfig.GetExpertMessageUrlKey),
					account.getUserId(), expert.getId());
			BaseResp br = HttpRequest.DoHttpRequest(url);
			if (br.isSuccess()) {
				JSONArray array = new JSONArray(br.getResponse());
				for (int i = 0; i < array.length(); i++) {
					JSONObject data = array.getJSONObject(i);
					ExpertMessage message = new ExpertMessage();
					message.setId(data.optInt("id"));
					message.setContent(data.optString("message"));
					int leaveUserId = data.optInt("senderId");
					message.setCreator(data.optString("senderMobile"));
					message.setTime(data.optString("messageTime"));
					if (leaveUserId == expert.getId()) {
						message.setIcon(expert.getIcon());
						message.setCreator(expert.getName());
					} else {
						message.setCreator("我");
						message.setIcon(account.getOwerIcon());
					}
					messages.add(message);
				}
			}
			return messages;
		} catch (Exception e) {

		}
		return null;
	}

	public List<NoReadMessageInfo> getNoReadMessages(Context context) {
		List<NoReadMessageInfo> messages = new ArrayList<NoReadMessageInfo>();
		try {
			String userId = SharedPreferencesUtil.getValue(context,
					SharedKey.Shared_UserId_Key, "");
			if (StringUtil.isEmpty(userId))
				return messages;

			/*
			 * Account account = AccountMgr.readAccountInfo(context);
			 * List<NoReadMessageInfo> messages = new
			 * ArrayList<NoReadMessageInfo>();
			 */
			String url = String.format(
					UrlConfig.getUrlByKey(UrlConfig.GetNoReadMessage), userId);
			BaseResp br = HttpRequest.DoHttpRequest(url);
			if (br.isSuccess()) {
				JSONArray array = new JSONArray(br.getResponse());
				for (int i = 0; i < array.length(); i++) {
					JSONObject data = array.getJSONObject(i);
					int leaveUserId = data.optInt("senderId");
					NoReadMessageInfo message = new NoReadMessageInfo();
					message.setLeaveUserId(leaveUserId);
					message.setLeaveUser(data.optString("leaveUser"));
					message.setCount(1);
					message.setLatestMessage(data.optString("message"));
					if (!data.isNull("senderMobile"))
						message.setLeaveMobile(data.optString("senderMobile")
								.trim());
					messages.add(message);
				}
			}
			return messages;
		} catch (Exception e) {
			Log.e("URL--NORead", e.getMessage());
		}
		return null;
	}

	public ExpertInfo getRandomExpert(Context context) {
		try {
			Account account = AccountMgr.readAccountInfo(context);
			String url = String.format(
					UrlConfig.getUrlByKey(UrlConfig.RandomExpertUrlKey),
					account.getMobile());
			BaseResp br = HttpRequest.DoHttpRequest(url);
			if (br.isSuccess()) {
				JSONObject data = new JSONObject(br.getResponse());
				ExpertInfo expert = new ExpertInfo();
				expert.setId(data.optInt("userId"));
				expert.setIcon(data.optString("icon"));
				expert.setName(data.optString("nickName"));
				expert.setPhone(data.optString("phone"));
				return expert;
			} else {
				if (br.getErrorCode().equals("224")) {
					lastErrorMessage = "抱歉，您不是不是天翼用户";
				} else if (br.getErrorCode().equals("225")) {
					lastErrorMessage = "您手机所在的地市尚未有辅导员，敬请期待";
				}
			}
		} catch (Exception e) {

		}
		return null;
	}

	public boolean assignExpert(Context context, ExpertInfo expert) {
		try {
			Account account = AccountMgr.readAccountInfo(context);
			String url = String.format(
					UrlConfig.getUrlByKey(UrlConfig.AssignExpertUrlKey),
					account.getMobile(), expert.getId(), expert.getPhone());
			BaseResp br = HttpRequest.DoHttpRequest(url);
			if (!br.isSuccess()) {
				if (br.getErrorCode().equals("554")) {
					lastErrorMessage = "抱歉，登录号码不存在";
				} else {
					lastErrorMessage = br.getDesc();
					if (TextUtils.isEmpty(lastErrorMessage))
						lastErrorMessage = "对不起，分配助理失败";
				}
				return false;
			} else {
				account.setHasExpert(true);
				account.setExpertId(expert.getId());
				account.setExpertName(expert.getName());
				AccountMgr.saveAccountInfo(context, account);
				return true;
			}
		} catch (Exception e) {

		}
		return false;
	}

	public boolean sendMessage(Context context, int receiverId, String message) {
		try {
			Account account = AccountMgr.readAccountInfo(context);
			String url = String.format(
					UrlConfig.getUrlByKey(UrlConfig.SendMessageUrlKey),
					account.getUserId(), receiverId);
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("message", message);
			BaseResp br = HttpRequest.DoHttpRepuestPost(url, params); // .DoHttpRequest(url);
			return br.isSuccess();
		} catch (Exception e) {

		}
		return false;
	}
}
